
var _ = require('lodash'),
    Q = require('q'),
    PublicEnum = require('../../../Base/server/controllers/Enum'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    stationWorkController = require('../../../Initialize/server/controllers/StationWork.server.controller'),
    qcStandardController = require('../../../QC/server/controllers/QCStandard.server.controller');

exports.getWrapperInfo = function(req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        terminalUniqueID = parameter.TerminalUniqueID;

    var wrapperInfo = {};
    queryBasicInfo(barcode).then(function (basicInfo) {
        wrapperInfo.basicInfo = basicInfo;
        return queryWork(terminalUniqueID);
    }).then(function (work) {
        _.merge(wrapperInfo.basicInfo, work);
        return queryQCStandard(wrapperInfo.basicInfo.ItemMaster, work.Work);
    }).then(function (qcStandard) {
        wrapperInfo.qcStandard = qcStandard;
        res.json({
            Data: wrapperInfo,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

exports.setWrapperMeasure = function(req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        work = parameter.Work,
        terminalUniqueID = parameter.TerminalUniqueID,
        users = parameter.Users;

    var bizRecord = {
        Work: work,
        WorkName: parameter.WorkName,
        Users: users,
        BusinessStatus: 1
    };
    queryTerminalInfo(terminalUniqueID).then(function (terminalInfo) {
        _.merge(bizRecord, terminalInfo);
        return queryOperation(barcode, work);
    }).then(function (operation) {
        _.merge(bizRecord, operation);
        return writeBizData(barcode, bizRecord);
    }).then(function (bizRecord) {
        var qcRecords = parameter.QCRecords,
            userId = users[0];
        _.forEach(qcRecords, function (qcRecord) {
            qcRecords.BizRecord = bizRecord._id;
            qcRecord.RowStatus = PublicEnum.RowStatus.Insert;
            qcRecord.CreatedBy = userId;
        });
        return writeQCRecords(qcRecords);
    }).then(function (qcRecords) {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

function queryBasicInfo (barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!barcodeMaster || barcodeMaster.BarcodeType != 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询物料错误';
            newErr.message = '无法识别的芯片，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve({
            ItemMaster: barcodeMaster.ItemMaster._id,
            MOCode: barcodeMaster.MOCode,
            ItemMasterCode: barcodeMaster.ItemMasterCode,
            ItemMasterName: barcodeMaster.ItemMasterName,
            Specification: barcodeMaster.ItemMaster.Specification,
            MOLotNumber: barcodeMaster.MOLotNumber,
            Users: barcodeMaster.Users
        });
    });

    return deferred.promise;
}

function queryWork (terminalUniqueID) {
    var deferred = Q.defer();

    stationWorkController.getStationWorksByTerminalUniqueID(terminalUniqueID, function(err, stationWorkRecords) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (stationWorkRecords.length > 0) {
            deferred.resolve({
                Work: stationWorkRecords[0].Work._id,
                WorkName: stationWorkRecords[0].Work.Name
            });
        } else {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询作业错误';
            newErr.message = '没有找到作业，请重新扫描！';
            deferred.reject(newErr);
        }
    });

    return deferred.promise;
}

function queryQCStandard (ItemMasterId, Work) {
    var deferred = Q.defer();

    qcStandardController.findQCStandard(ItemMasterId, Work, function (err, qcStandards) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!qcStandards) {
            deferred.resolve([]);
            return;
        }
        var result = [];
        _.forEach(qcStandards, function (qcStandard) {
            result.push({
                QCStandard: qcStandard._id,
                QCNorm: qcStandard.QCNorm._id,
                QCNormName: qcStandard.QCNorm.Name,
                StandardValue: qcStandard.StandardValue,
                ValueUpperLimit: qcStandard.ValueUpperLimit,
                ValueLowerLimit: qcStandard.ValueLowerLimit
            });
        });
        deferred.resolve(result);
    });

    return deferred.promise;
}

function queryTerminalInfo (terminalUniqueID) {
    var deferred = Q.defer();

    terminalController.findByUniqueID(terminalUniqueID, function (err, terminalRecord) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (terminalRecord == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询终端错误';
            newErr.message = '请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve({
            Terminal: terminalRecord._id,
            TerminalName: terminalRecord.Name
        });
    });

    return deferred.promise;
}

function queryOperation (barcode, work) {
    var deferred = Q.defer();
    
    barcodeMasterController.findBarcodeMaster(barcode, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        operationController.findByItemMasterAndWork(record.ItemMaster._id, work, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            var data = {
                BarcodeMaster: record._id,
                WorkLocation: record.WorkLocation,
                WorkLocationName: record.WorkLocationName
            };
            if (result) {
                _.merge(data, {
                    Operation: result._id,
                    OperationName: result.Name
                });
            }
            deferred.resolve(data);
        });
    });

    return deferred.promise;
}

function writeBizData (barcode, bizRecord) {
    var deferred = Q.defer();
    
    bizRecordController.insert(bizRecord, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        delete bizRecord.BarcodeMaster;
        barcodeMasterController.updateByValue(barcode, bizRecord, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(record);
        });
    });

    return deferred.promise;
}

function writeQCRecords (qcRecords) {
    var deferred = Q.defer();

    Transaction.BatchSaveByTran([
            {EntityName: 'QCRecord', Records: qcRecords}
        ],
        function(err, result){
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve(result);
        }
    );

    return deferred.promise;
}